package czk.concrent.review.synControl;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/7/22 23:37
 */
public class ReentrantLockSynControl {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLockDemo reentrantLockDemo=new ReentrantLockDemo(5);
        Condition condition1=reentrantLockDemo.newCondition();
        Condition condition2=reentrantLockDemo.newCondition();
        Condition condition3=reentrantLockDemo.newCondition();
        new Thread(()->{
            reentrantLockDemo.print("A",condition1,condition2);
        }).start();
        new Thread(()->{
            reentrantLockDemo.print("B",condition2,condition3);
        }).start();
        new Thread(()->{
            reentrantLockDemo.print("C",condition3,condition1);
        }).start();
        Thread.sleep(2*1000);
        reentrantLockDemo.lock();
        try {
            condition1.signal();
        }finally {
            reentrantLockDemo.unlock();
        }
    }
}
class ReentrantLockDemo extends ReentrantLock {
    // 循环条数
    private int loopNum;

    public ReentrantLockDemo(int loopNum) {
        this.loopNum = loopNum;
    }
    public void print(String content, Condition current,Condition next){
        for (int i = 0; i < loopNum ;i++) {
            try {
                lock();
                current.await();
                System.out.print(content);
                next.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                unlock();
            }
        }
        }

}
